<?php
class Tags extends Config
{
	var $tableName = "tags"; //name of table
	private $tagId; //tag identifier
	var $tag; //tag string
	private  $tagIteration; //iterations of tag
	var $inputTagsString;
	
	private function checkTag()
	{
		$query0 = "SELECT * FROM `". $this -> DB_PREFIX . $this -> tableName ."` 
					WHERE `tag` = '". mysql_real_escape_string($this -> tag) ."' LIMIT 1";
		$select0 = $this -> sql($query0);
		if (mysql_num_rows($select0) == 1)
		{
			$data0 = mysql_fetch_array($select0);
			$this -> tagId = $data0['id'];
			$this -> tagIteration = $data0['iteration'];
			return true;
		}
		else
		{
			return false;
		}
	}
	
	private function addTag()
	{
		$queryText0 = "INSERT INTO `". $this -> DB_PREFIX . $this -> tableName ."` SET 
			`tag`= '". mysql_real_escape_string($this -> tag) . "',
			`iteration` = 1";
		$this -> sql($queryText0);
	}

	private function delTag()
	{
		$queryText0 = "DELETE FROM `". $this -> DB_PREFIX . $this -> tableName ."`  
			WHERE `id`= '". $this -> tagId . "'";
		$this -> sql($queryText0);
	}
	
	private function incIteration()
	{
		$queryText0 = "UPDATE `". $this -> DB_PREFIX . $this -> tableName ."`  
			SET `iteration` = `iteration` + 1
			WHERE `id`= '". $this -> tagId . "'";
		$this -> sql($queryText0);
	}
	
	private function decIteration()
	{
		$queryText0 = "UPDATE `". $this -> DB_PREFIX . $this -> tableName ."`  
			SET `iteration` = `iteration` - 1
			WHERE `id`= '". $this -> tagId . "'";
		$this -> sql($queryText0);
	}
	
	//Actions
	function addPost()
	{
		if (strpos($this -> inputTagsString, ","))
		{
			$tags = explode(',', $this -> inputTagsString);
			
			foreach($tags as $tag) 
			{
				$this -> tag = urlencode(trim($tag));
				if ($this -> checkTag())
				{
					$this -> incIteration();
				}
				else
				{
					$this -> addTag();
				}
			}
		}
		else
		{
			$this -> tag = urlencode(trim($this -> inputTagsString));
			if ($this -> checkTag())
			{
				$this -> incIteration();
			}
			else
			{
				$this -> addTag();
			}
		}
	}
	
	function delPost()
	{
		if (strpos($this -> inputTagsString, ","))
		{
			$tags = explode(',', $this -> inputTagsString);
			
			foreach($tags as $tag) 
			{
				$this -> tag = urlencode(trim($tag));
				//may be tag empty?
				if ($this -> checkTag())
				{
					if ($this -> tagIteration > 1)
					{
						$this -> decIteration();
					}
					else
					{
						$this -> delTag();
					}
				}
			}
		}
		else
		{
			$this -> tag = urlencode(trim($this -> inputTagsString));
			//may be tag empty?
			if ($this -> checkTag())
			{
				if ($this -> tagIteration > 1)
				{
					$this -> decIteration();
				}
				else
				{
					$this -> delTag();
				}
			}
		}
	}
	
	
	
}

?>